const fs = require('fs').promises;
const path = require('path');
/**
 * 导入模块拼接函数
 * @param {app } param0 当前koa实例
 * @param {root } param1 root 对象
 */
function resolveVue(root) {
    const compilerpkgPath = path.join(root, 'node_module', '@vue/compiler-sfc/package.json');

    const compilerpkg = require(compilerpkgPath) //拿到对应的json

    const compilerPath = path.join(path.dirname(compilerpkg), compilerpkg.main);

    const resolvePath = (name) => path.resolve(root, 'node_module', `@vue/${name}/dist/${name}.esm-bundler.js`)

    const runtimeDomPath = resolvePath('runtime-dom')
    const runtimeCorePath = resolvePath('runtime-core')
    const reactivityPath = resolvePath('reactivity')
    const sharedPath = resolvePath('shared')
    //创建映射关系
    return {
        compiler: compilerPath,
        '@vue/runtime-dom': runtimeDomPath,
        '@vue/runtime-core': runtimeCorePath,
        '@vue/reactivity': reactivityPath,
        '@vue/shared': sharedPath,
        vue: runtimeDomPath
    }
}

const moduleREG = /\/@module\//;
const moduleResolvePlugin = ({ app, root }) => {
    const vueResolve = resolveVue(root) //解析文件表

    app.use(async (ctx, next) => {
        if (!moduleREG.test(ctx.path)) { //匹配开头是否是modules
            return next();
        }
        const id = ctx.path.replace(moduleREG, '');
        ctx.type = 'js'
        const content = await fs.readFile(vueResolve[id], 'utf-8')
        ctx.body = content;
    })
}

module.exports = moduleResolvePlugin